// pages/mch/order/create.js
const App = getApp()
import Qiniu from '../../../utils/qiniu'
import Kits from '../../../utils/kits'
import Util from '../../../utils/util'

Page({
  data: {
    init: false,
    car: {},
    mem: {},

    mob: '',
    name: '',
    idno: '',
    caddr: '',

    idc: '',
    dlc: '',

    timeok: 'check',
    begin: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    close: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    hdays: '',

    type: '1',
    area: '',
    addr: '',
    locs: '',

    price: {},
    depotype: 1,

    feeDetails: [],
    feeDetail: false,

    vinfo: '',
    vcode: '',
    idca: '',
    idcb: '',
    dlca: '',
    dlcb: '',

    mile: '',
    thing: '',
    photo: [],
    video: [],
    detail: [],

    butText: '获取验证码',
    butDisabled: false,
    interval: undefined,
    sec: 0,

    oilOpts: [{
      id: 1,
      name: '1 / 8'
    }, {
      id: 2,
      name: '2 / 8'
    }, {
      id: 3,
      name: '3 / 8'
    }, {
      id: 4,
      name: '半箱油'
    }, {
      id: 5,
      name: '5 / 8'
    }, {
      id: 6,
      name: '6 / 8'
    }, {
      id: 7,
      name: '7 / 8'
    }, {
      id: 8,
      name: '满箱油'
    }],
    oilIndex: 1,
  },
  onLoad(options) {
    let now = Kits.getNextTime(new Date().getTime())

    this.doSetDates(now, now.addDays(2))

    this.execLoad(options.cid)
  },
  onUnload() {
    if (this.data.interval != undefined) {
      clearInterval(this.data.interval)
    }
  },
  execLoad(cid) {
    App.doPost({
      uri: '/app/merchant/car/detail',
      body: {
        id: cid
      },
      fnSucc: resp => {
        resp.data.price.pdpStr = Kits.fmtMoneyString(resp.data.price.pdp)
        resp.data.price.pmpStr = Kits.fmtMoneyString(resp.data.price.pmp)
        resp.data.price.mdpStr = Kits.fmtMoneyString(resp.data.price.mdp)
        resp.data.price.depositStr = Kits.fmtMoneyString(resp.data.price.deposit)
        this.setData({
          init: true,
          car: resp.data,
        })
        this.execCheckTime()
        this.execCalcPrice()
      }
    })
  },
  doTypeChange(e) {
    this.setData({
      type: parseInt(e.currentTarget.dataset.type)
    })
  },
  // 检查租赁时间是否可用
  execCheckTime() {
    if (!this.data.car.id) {
      return
    }
    this.setData({
      timeok: 'check'
    })
    App.doPost({
      uri: '/app/base/biz/car/state',
      body: {
        id: this.data.car.id,
        begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
        close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss')
      },
      fnSucc: resp => {
        this.setData({
          timeok: resp.data.flag ? 'true' : 'false'
        })
      }
    })
  },
  // 计算价格
  execCalcPrice() {
    if (!this.data.init) {
      return
    }
    if (!this.data.car.id) {
      return
    }
    this.setData({
      price: {}
    })

    if ((this.data.svc_onsite || this.data.svc_remote) && this.data.onsite_locs == '') {
      return
    }
    let body = {
      cid: this.data.car.id,
      mem: true,
      begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
      close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
      method: 1,
      mine: {},
      entrust: {
        day: 0,
      },
      custom: {
        day: 0
      },
      onsite: {
        flag: this.data.type == '2',
        area: this.data.area,
        addr: this.data.addr,
        locs: this.data.locs
      },
      remote: {
        flag: this.data.type == '2',
        area: this.data.area,
        addr: this.data.addr,
        locs: this.data.locs
      },
      service: {
        bins: false,
        dins: false,
        tins: false,
        free: false
      },
      deposit: this.data.depotype
    }
    App.doPost({
      uri: '/app/base/order/create/price/calc',
      body: body,
      fnSucc: resp => {
        resp.data.totalStr = Kits.fmtMoneyString(resp.data.total)
        resp.data.brokerageStr = Kits.fmtMoneyString(resp.data.bamt)
        this.setData({
          price: resp.data,
          feeDetails: resp.data.fees,

        })
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  doShowFeeDetails() {

    this.setData({
      feeDetail: true
    })
  },
  doHideFeeDetails() {
    this.setData({
      feeDetail: false
    })
  },
  // 更换押金方式
  doDepoTypeChange(e) {
    this.setData({
      depotype: parseInt(e.currentTarget.dataset.type)
    })
  },
  // 选择地点
  doSelectLocs() {
    let lng = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[0]) : undefined
    let lat = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[1]) : undefined
    wx.chooseLocation({
      longitude: lng,
      latitude: lat,
      success: (res) => {

        let locs = res.longitude.toFixed(6) + ',' + res.latitude.toFixed(6)
        App.doPost({
          uri: '/comm/tool/locs/info',
          body: {
            locs: locs
          },
          fnSucc: resp => {

            this.setData({
              addr: res.name,
              area: resp.data.area.code + "",
              locs: locs
            })

            this.execCalcPrice()
          },
          fnFail: () => {
            Util.Toast.fail('未知地点信息')
          }
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  // 设置日期
  doSetDates(beginTime, closeTime) {
    let begin = {
      value: beginTime.getTime(),
      year: beginTime.format('yyyy'),
      date: beginTime.format('MM月dd日'),
      time: beginTime.format('HH:mm'),
    }
    let close = {
      value: closeTime.getTime(),
      year: closeTime.format('yyyy'),
      date: closeTime.format('MM月dd日'),
      time: closeTime.format('HH:mm'),
    }
    this.setData({
      begin: begin,
      close: close,
      hdays: Kits.getDateMemo(beginTime, closeTime)
    })
    this.execCheckTime()
    this.execCalcPrice()
  },

  // 跳转选择日期界面
  toSelectDate() {
    wx.navigateTo({
      url: `/pages/order/calendar?carid=${this.data.car.id}&begin=${this.data.begin.value}&close=${this.data.close.value}`,
      events: {
        enter: (e) => {
          this.doSetDates(new Date(e.begin), new Date(e.close))
        }
      }
    })
  },
  // 查询会员
  execQuery() {
    if (this.data.mob.length != 11) {
      this.setData({
        mem: {},
        name: '',
        idno: '',
        idc: {},
        dlc: {},
        caddr: ''
      })
      return
    }
    App.doPost({
      uri: '/comm/biz/member/query',
      body: {
        mob: this.data.mob
      },
      fnSucc: resp => {
        if (!resp.data.id) {
          return
        }
        this.setData({
          mem: resp.data,
          name: resp.data.idc.name,
          idno: resp.data.idno,
          idc: resp.data.idc,
          dlc: resp.data.dlc,
          caddr: resp.data.add || resp.data.idc.addr
        })
      }
    })
  },
  execGetVcode() {
    if (this.data.mob.length != 11) {
      return
    }
    if (this.data.butDisabled) {
      return
    }
    this.setData({
      loading: true,
      butDisabled: true
    })
    App.doPost({
      uri: '/app/base/tool/sms/captcha',
      body: {
        mob: this.data.mob
      },
      fnSucc: resp => {
        this.setData({
          sec: resp.data.limit,
          vinfo: resp.data.vinfo,
        })
        let int = setInterval(() => {
          if (this.data.sec <= 1) {
            clearInterval(this.data.interval)
            this.setData({
              sec: 0,
              butText: '验证码',
              butDisabled: false,
              interval: undefined
            })
            return
          }
          this.data.sec = this.data.sec - 1
          this.setData({
            sec: this.data.sec,
            butText: `${this.data.sec} 秒后重发`
          })
        }, 1000);
        this.setData({
          interval: int
        })
        if (App.Global.Debug && resp.data.vcode) {
          wx.showToast({
            icon: 'none',
            title: '测试账号，验证码已自动填写'
          })
          this.setData({
            vcode: resp.data.vcode
          })
        } else {
          wx.showToast({
            title: '验证码已发送'
          })
        }

      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
        this.setData({
          butDisabled: false,
        })
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  doCertChange(e) {
    let type = e.target.dataset.type
    console.log(e.detail)
    let odata = {}
    odata[type] = e.detail.url
    if (type == 'idca' && e.detail.ocr.idno) {
      odata.name = e.detail.ocr.name
      odata.idno = e.detail.ocr.idno
      odata.caddr = this.data.caddr || e.detail.ocr.addr
    }
    this.setData({
      ...odata
    })
  },


  doChooseItem(e) {
    let type = e.currentTarget.dataset.type
    wx.chooseMedia({
      count: 1,
      mediaType: [type == 'video' ? 'video' : 'image'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        this.execUpload(res.tempFiles[0].tempFilePath, type)
      }
    })
  },
  execUpload(path, type) {
    App.doPost({
      uri: '/comm/tool/file/qiniu/info',
      body: {
        type: type == 'video' ? 'Video' : 'Image'
      },
      fnSucc: resp => {
        let key = resp.data.path + resp.data.fileid + '.' + path.split('.').pop()?.toLowerCase()
        Qiniu.upload(path, (res) => {

          if (type == 'photo') {
            let srcs = this.data.photo
            srcs[srcs.length] = res.imageURL
            this.setData({
              photo: srcs
            })
          }
          if (type == 'video') {
            let srcs = this.data.video
            srcs[srcs.length] = res.imageURL
            this.setData({
              video: srcs
            })
          }
          if (type == 'detail') {
            let srcs = this.data.detail
            srcs[srcs.length] = res.imageURL
            this.setData({
              detail: srcs
            })
          }
        }, (err) => {
          console.log(err)
        }, {
          region: 'NCN',
          key: key,
          uptoken: resp.data.token,
          uptokenFunc: null,
          uptokenURL: null,
          domain: resp.data.domain,
          shouldUseQiniuFileName: false,
        }, () => {

        }, () => {

        })
      },
      fnFail: resp => {
        App.doAlert('出错啦', `上传失败，[${resp.stat.err}] ${resp.stat.msg}`)
      }
    })
  },
  doPreviewItem(e) {
    let type = e.currentTarget.dataset.type
    let sources = []

    this.data[type].forEach(p => {
      sources[sources.length] = {
        url: p,
        type: type == 'video' ? 'video' : 'image'
      }
    })

    let current = this.data[type].findIndex(p => p == e.currentTarget.dataset.url)
    console.log(sources, current)
    wx.previewMedia({
      sources: sources,
      current: current
    })
  },
  doDeleteItem(e) {
    if (e.currentTarget.dataset.type == 'photo') {
      this.data.photo.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        photo: this.data.photo
      })
    }
    if (e.currentTarget.dataset.type == 'video') {
      this.data.video.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        video: this.data.video
      })
    }
    if (e.currentTarget.dataset.type == 'detail') {
      this.data.detail.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        detail: this.data.detail
      })
    }

  },
  execSave() {
    if (!this.data.vinfo) {
      Util.Notify.warn(`请获取验证码`)
      return
    }
    if (!this.data.vcode) {
      Util.Notify.warn(`请填写验证码`)
      return
    }

    if (!this.data.idca && !this.data.idc.id) {
      Util.Notify.warn(`请上传身份证`)
      return
    }
    if (!this.data.idcb && !this.data.idc.id) {
      Util.Notify.warn(`请上传身份证`)
      return
    }
    if (!this.data.dlca && !this.data.dlc.id) {
      Util.Notify.warn(`请上传驾驶证`)
      return
    }
    if (!this.data.dlcb && !this.data.dlc.id) {
      Util.Notify.warn(`请上传驾驶证`)
      return
    }
    if (!this.data.mile) {
      Util.Notify.warn(`请填写行驶里程`)
      return
    }
    if (this.data.photo.length == 0 && this.data.video.length == 0) {
      Util.Notify.warn(`请上传验车图片或视频`)
      return
    }

    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/merchant/order/create',
      body: {
        customer: {
          id: this.data.mem.id || '',
          mob: this.data.mob,
          name: this.data.name,
          addr: this.data.caddr,
          sno:this.data.idno
        },
        captcha: {
          info: this.data.vinfo,
          code: this.data.vcode
        },
        idc: {
          pica: this.data.idca,
          id: this.data.idc.id || '',
          picb: this.data.idcb,
         
        },
        dlc: {
          pica: this.data.dlca,
          id: this.data.dlc.id || '',
          picb: this.data.dlcb
        },
        info: {
          mile: parseInt(this.data.mile),
          fuel: parseInt(this.data.oilIndex) + 1,
          thing: this.data.thing
        },
        photo: this.data.photo,
        video: this.data.video,
        detail: this.data.detail,
        cid: this.data.car.id,
        begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
        close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
        onsite: {
          flag: this.data.type == '2',
          area: this.data.area,
          addr: this.data.addr,
          locs: this.data.locs
        },
        remote: {
          flag: this.data.type == '2',
          area: this.data.area,
          addr: this.data.addr,
          locs: this.data.locs
        },
        service: {
          bins: false,
          dins: false,
          tins: false,
          free: false
        },
        deposit: this.data.depotype,
        memo: this.data.memo,
      },
      fnSucc: (resp) => {
        wx.pub("ReloadOrderList", {})
        Util.Toast.succ(`下单成功`)
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/mch/order/detail?oid=${resp.data.id}`,
          })
        }, 1000);
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  doChangeOilSlider(e){
    console.log(e.detail.value)
    this.setData({
      oilIndex: e.detail.value
    })
  },
})